# -*- coding: utf-8 -*-
# created on 2016/12/20

from sympy import Symbol, Union, sympify
from sympy.core.function import UndefinedFunction
from mathsolver.functions.hanshu.dandiaoqujian import DanDiaoQuJian
from mathsolver.functions.hanshu.abstract_hanshu_dingyiyu import AbstractHanShuDingYiYu
from mathsolver.functions.base import BaseFunction, BaseEq, new_latex
from mathsolver.functions.sympy_utils import get_all_child


class AbstractHansShuDanDiao(BaseFunction):
    """判断抽象函数单调性
    已知 f(x) 在 区间 I 上单调性，求 y = a*f[g(x)] + b 的单调性
    t = g(x)
    u = f(t)
    y = a*u + b
    """

    def solver(self, *args):
        fx, qujian, dandiao_fx, y_q, dandiao_q = args
        expr = sympify(y_q.value[1])

        # 求抽象函数定义域
        dingyiyu_step = AbstractHanShuDingYiYu().solver(fx, y_q, qujian)
        self.steps.extend(dingyiyu_step.steps)
        dingyiyu = dingyiyu_step.output[0]

        # 抽取出 t, u, y, 其中 u = f(t) 单调性已知

        # 求出 gx 的单调区间
        fgx = get_all_child(expr, lambda xx: isinstance(xx.func, UndefinedFunction))[0]
        gx = fgx.args[0]
        up, down = DanDiaoQuJian().solver(BaseEq(['y', gx]), dingyiyu).output[0].value

        x = Symbol('x')
        a = expr.subs(fgx, x).coeff(x)
        dandiao_y = '增' if a > 0 else '减'
        self.steps.append(["", "一次函数 y = %s 定义域上为单调%s函数" % (new_latex(expr.subs(fgx, x)), dandiao_y)])

        # 根据单个函数单调性，判断复合函数单调性
        dandiaos = [dandiao_fx, dandiao_y]
        dandiao_zeng = []
        dandiao_jian = []
        if up:
            self.steps.append(["", " %s 的单调增区间是 %s" % (new_latex(gx), new_latex(up))])
            if sum(dandiao == '增' for dandiao in dandiaos) % 2 == 0:
                # 偶数个'增' -> 一共奇数个'增' -> 单调增
                dandiao_zeng.append(up)
            else:
                # 奇数个'增' -> 一共偶数个'增' -> 单调减
                dandiao_jian.append(up)
        if down:
            self.steps.append(["", " %s 的单调减区间是 %s" % (new_latex(gx), new_latex(down))])
            if sum(dandiao == '增' for dandiao in dandiaos) % 2 == 0:
                # 偶数个'增' -> 一共偶数个'增' -> 单调减
                dandiao_jian.append(down)
            else:
                # 奇数个'增' -> 一共奇数个'增' -> 单调增
                dandiao_zeng.append(down)

        # 结果
        dandiao_zeng = Union(dandiao_zeng)
        dandiao_jian = Union(dandiao_jian)

        if '增' in dandiao_q:
            res = dandiao_zeng
            self.steps.append(["", "所以 %s 的单调增区间为 %s" % (y_q.printing(), new_latex(dandiao_zeng))])
        elif '减' in dandiao_q:
            self.steps.append(["", "所以 %s 的单调减区间为 %s" % (y_q.printing(), new_latex(dandiao_jian))])
            res = dandiao_jian
        else:
            self.steps.append(["", "所以 %s 的单调增区间为 %s, 单调减区间为 %s" % (y_q.printing(), new_latex(dandiao_zeng), new_latex(dandiao_jian))])
            res = [dandiao_zeng, dandiao_jian]

        self.output.append(res)
        self.label.add("判断抽象函数单调性")
        return self


if __name__ == '__main__':
    pass
